{% extends "admin/layout.html" %}

{% block content %}
<div class="container-fluid px-4">
    <!-- 页面标题区域 -->
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1 fw-bold">部门管理</h2>
            <p class="text-muted mb-0">管理系统组织架构与部门层级关系</p>
        </div>
        <a href="{{ url_for('admin.admin_department.add_department') }}" class="btn btn-primary">
            <i class="fas fa-plus me-1"></i> 新建部门
        </a>
    </div>

    <!-- 统计卡片 -->
    <div class="row mb-4">
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <h6 class="text-muted mb-1">总部门数</h6>
                            <h4 class="mb-0 fw-bold">{{ stats.total_departments }}</h4>
                        </div>
                        <div class="flex-shrink-0">
                            <i class="fas fa-sitemap fa-2x text-primary"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <h6 class="text-muted mb-1">员工总数</h6>
                            <h4 class="mb-0 fw-bold">{{ stats.total_members }}</h4>
                        </div>
                        <div class="flex-shrink-0">
                            <i class="fas fa-users fa-2x text-success"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <h6 class="text-muted mb-1">一级部门</h6>
                            <h4 class="mb-0 fw-bold">{{ stats.top_level_count }}</h4>
                        </div>
                        <div class="flex-shrink-0">
                            <i class="fas fa-layer-group fa-2x text-info"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-md-3 col-sm-6 mb-3">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body">
                    <div class="d-flex align-items-center">
                        <div class="flex-grow-1">
                            <h6 class="text-muted mb-1">最近更新</h6>
                            <h4 class="mb-0 fw-bold">{{ stats.last_update }}</h4>
                        </div>
                        <div class="flex-shrink-0">
                            <i class="fas fa-history fa-2x text-warning"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 部门列表卡片 -->
    <div class="card border-0 shadow-sm">
        <div class="card-header bg-white py-3 d-flex flex-wrap justify-content-between align-items-center gap-3">
            <h5 class="mb-0"><i class="fas fa-list me-2"></i>部门列表</h5>
            <div class="d-flex gap-2 flex-wrap">
                <div class="btn-group btn-group-sm">
                    <button class="btn btn-outline-secondary" id="collapseAll" title="全部折叠">
                        <i class="fas fa-compress-alt"></i>
                    </button>
                    <button class="btn btn-outline-primary" id="expandFirstLevel" title="展开一级">
                        <i class="fas fa-expand-alt"></i>
                    </button>
                </div>
            </div>
        </div>
        <div class="card-body p-0">
            {% if department_tree %}
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-light">
                        <tr>
                            <th>部门名称</th>
                            <th class="text-end">操作</th>
                        </tr>
                    </thead>
                    <tbody id="deptTree">
                        {% macro render_department(dept, level=0) %}
                        <tr data-dept-id="{{ dept.id }}" data-parent-id="{{ dept.parent_id }}"
                            data-level="{{ level }}" class="{% if level > 0 %}child-row{% endif %}">
                            <td style="padding-left: {{ level * 28 + 12 }}px">
                                {% if dept.children %}
                                <button class="btn btn-sm btn-toggle me-2" data-bs-toggle="collapse"
                                        data-bs-target="#children-{{ dept.id }}">
                                    <i class="fas fa-chevron-{% if level == 0 %}down{% else %}right{% endif %}"></i>
                                </button>
                                {% else %}
                                <span class="me-4"></span>
                                {% endif %}
                                <span class="dept-name fw-medium">{{ dept.name }}</span>
                                {% if dept.member_count %}
                                <span class="badge bg-light text-dark ms-2">{{ dept.member_count }}人</span>
                                {% endif %}
                            </td>
                            <td class="text-end">
                                <div class="btn-group btn-group-sm">
                                    <a href="{{ url_for('admin.admin_department.add_department', parent_id=dept.id) }}"
                                       class="btn btn-sm btn-light" data-bs-toggle="tooltip" title="添加子部门"
                                       aria-label="添加子部门">
                                        <i class="fas fa-plus text-success"></i>
                                    </a>
                                    <a href="{{ url_for('admin.admin_department.edit_department', id=dept.id) }}"
                                       class="btn btn-sm btn-light" data-bs-toggle="tooltip" title="编辑部门"
                                       aria-label="编辑部门">
                                        <i class="fas fa-edit text-primary"></i>
                                    </a>
                                <a href="{{ url_for('admin.admin_department.delete_department', id=dept.id) }}"
                                   class="btn btn-sm btn-light delete-btn"
                                   data-bs-toggle="tooltip" title="删除部门"
                                   onclick="return confirm('确定要删除此部门吗？此操作不可恢复。');"
                                   aria-label="删除部门">
                                    <i class="fas fa-trash text-danger"></i>
                                </a>
                                </div>
                            </td>
                        </tr>
                        {% if dept.children %}
                        <tr class="collapse {% if level == 0 %}show{% endif %}" id="children-{{ dept.id }}">
                            <td colspan="2" class="p-0 border-0">
                                <table class="table mb-0">
                                    {% for child in dept.children %}
                                        {{ render_department(child, level + 1) }}
                                    {% endfor %}
                                </table>
                            </td>
                        </tr>
                        {% endif %}
                        {% endmacro %}

                        {% for dept in department_tree %}
                            {{ render_department(dept) }}
                        {% endfor %}
                    </tbody>
                </table>
            </div>
            {% else %}
            <div class="text-center py-5 text-muted">
                <i class="fas fa-sitemap fa-3x mb-3 opacity-25"></i>
                <p class="mb-2">暂无部门数据</p>
                <p class="small mb-0">点击右上角"新建部门"按钮创建第一个部门</p>
            </div>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
    tooltipTriggerList.map(function (tooltipTriggerEl) {
        return new bootstrap.Tooltip(tooltipTriggerEl);
    });

    // 树形结构交互
    document.querySelectorAll('.btn-toggle').forEach(btn => {
        btn.addEventListener('click', function(e) {
            e.stopPropagation();
            const icon = this.querySelector('i');
            icon.classList.toggle('fa-chevron-right');
            icon.classList.toggle('fa-chevron-down');
        });
    });

    // 全部折叠
    document.getElementById('collapseAll').addEventListener('click', () => {
        document.querySelectorAll('.btn-toggle').forEach(btn => {
            const icon = btn.querySelector('i');
            icon.classList.add('fa-chevron-right');
            icon.classList.remove('fa-chevron-down');
        });
        document.querySelectorAll('.collapse').forEach(collapse => {
            new bootstrap.Collapse(collapse).hide();
        });
    });

    // 展开一级部门
    document.getElementById('expandFirstLevel').addEventListener('click', () => {
        // 折叠所有
        document.querySelectorAll('.collapse').forEach(collapse => {
            new bootstrap.Collapse(collapse).hide();
        });

        // 重置所有图标
        document.querySelectorAll('.btn-toggle i').forEach(icon => {
            icon.classList.remove('fa-chevron-down');
            icon.classList.add('fa-chevron-right');
        });

        // 只展开一级部门
        document.querySelectorAll('tr[data-level="0"]').forEach(row => {
            const toggleBtn = row.querySelector('.btn-toggle');
            if (toggleBtn) {
                const childContainer = document.getElementById(`children-${row.dataset.deptId}`);
                if (childContainer) {
                    new bootstrap.Collapse(childContainer).show();
                    toggleBtn.querySelector('i').classList.remove('fa-chevron-right');
                    toggleBtn.querySelector('i').classList.add('fa-chevron-down');
                }
            }
        });
    });

    // 删除功能确认
    document.querySelectorAll('.delete-btn').forEach(btn => {
        btn.addEventListener('click', function(e) {
            if (!confirm(this.getAttribute('data-confirm') || '确定要删除此部门吗？')) {
                e.preventDefault();
            }
        });
    });
            const deptName = this.closest('tr').querySelector('.dept-name').textContent;
            if (!confirm(`确定要删除"${deptName}"部门吗？此操作不可恢复。`)) return;

            try {
                const response = await fetch(`/departments/delete/${this.dataset.deptId}`, {
                    method: 'DELETE'
                });

                if (response.ok) {
                    // 移除被删除的节点
                    const row = this.closest('tr[data-dept-id]');
                    row.nextElementSibling?.remove(); // 移除子节点容器
                    row.remove();

                    // 显示成功消息
                    const alertDiv = document.createElement('div');
                    alertDiv.className = 'alert alert-success alert-dismissible fade show';
                    alertDiv.innerHTML = `
                        <i class="fas fa-check-circle me-2"></i>部门删除成功
                        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                    `;
                    document.querySelector('.main-content').prepend(alertDiv);
                } else {
                    throw new Error('删除失败');
                }
            } catch (error) {
                alert('删除失败，请稍后重试');
            }
        });
    });
});
</script>

<style>
/* 整体布局优化 */
.card {
    border-radius: 12px;
}

.card-header {
    border-bottom: 1px solid rgba(0,0,0,0.05);
}

/* 树形结构样式 */
.btn-toggle {
    width: 24px;
    height: 24px;
    padding: 0;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border: 1px solid #e9ecef;
    border-radius: 6px;
    transition: all 0.2s;
    background: #f8f9fa;
}

.btn-toggle:hover {
    background-color: #e9ecef;
    border-color: #dee2e6;
}

.btn-toggle i {
    font-size: 0.7rem;
    transition: transform 0.2s;
}

.table td {
    vertical-align: middle;
    padding: 1rem;
    border-color: #f8f9fa;
}

.table th {
    padding: 0.75rem 1rem;
    font-weight: 600;
    background: #f8f9fa;
    border-color: #f8f9fa;
}

.child-row {
    background-color: rgba(248, 249, 250, 0.6);
}

.child-row:hover {
    background-color: rgba(13, 110, 253, 0.03);
}

/* 操作按钮样式 */
.btn-group .btn {
    border-radius: 6px;
    padding: 0.4rem 0.5rem;
    transition: all 0.2s;
}

.btn-group .btn:hover {
    background-color: #f8f9fa;
    transform: translateY(-1px);
}

/* 搜索框样式 */
.input-group-text {
    border-right: none;
    background: transparent;
}

#searchInput {
    border-left: none;
    background: transparent;
}

#searchInput:focus {
    box-shadow: none;
    border-color: #ced4da;
    background: #fff;
}

/* 统计卡片样式 */
.stat-card {
    transition: transform 0.2s;
}

.stat-card:hover {
    transform: translateY(-3px);
}

/* 空状态样式 */
.fa-sitemap {
    opacity: 0.15;
}

/* 响应式调整 */
@media (max-width: 768px) {
    .card-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }

    .input-group {
        width: 100% !important;
    }

    .table-responsive {
        border-radius: 0 0 12px 12px;
    }

    .btn-group {
        align-self: flex-end;
    }
}
</style>
{% endblock %}